import socket
import thread
import wx
import wx.grid
from wx.lib import newevent
import time

EvtAddHost, EVT_ADDHOST = newevent.NewEvent()

MAJOR_VERSION = 1
MINOR_VERSION = 0

PORT = 4444



class ServerConn:
    def __init__(self, s, addr):
    
        self.s = s
        self.addr = addr
        
    def desc(self):
        print self.s
        print self.addr


def ListenProc():
    '''This thread will listen for the connection. If a connection is accepted. It will notify the UI will a ServerConn instance'''
    print 'Start listening...'
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    if not s:
        print '[WARNNING] Create socket failed!'
        
    s.bind(('0.0.0.0', PORT))
    s.listen(5)
    
    while True:
        s_remote,addr =  s.accept()
        print (s_remote,addr)
        frame.AddHost(ServerConn(s_remote, addr))
        #conn = ServerConn(s, addr)
        #conn.desc()
        
        
    
        
def ClientStart():
    thread.start_new_thread(ListenProc, ())    
        
        
  
class HostsList(wx.ListCtrl):
    def __init__(self, parent):
        wx.ListCtrl.__init__(self, parent, style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.LC_HRULES)
        self.InsertColumn(0, 'HostName', wx.LIST_FORMAT_RIGHT, 150)
        self.InsertColumn(1, 'Address', 0, 150)
        self.InsertColumn(2, 'Delay(ms)', 0, 150)
        self.Append(['aa', 'bb'])
        
class HostsWindow(wx.Frame):
    def __init__(self, parent, id, title):
        self.Bind(EVT_ADDHOST, self.OnAddHost)
    
        wx.Frame.__init__(self, parent, id, title, size=(800, 600))
        self.list = HostsList(self)
        self.Show(True)
    
    def OnAddHost(self, event):
        print event
        
    def AddHost(self, host):
        wx.PostEvent(self, EvtAddHost(event = '', arguments=''))
        
        
app = wx.PySimpleApp()
frame = HostsWindow(None, wx.ID_ANY, 'Hosts')
ClientStart()

app.MainLoop()
    

 

    
